-- Grow-a-Garden 自动交易系统
-- 基于交易拦截器实现的自动交易功能

local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local UserInputService = game:GetService("UserInputService")

local LocalPlayer = Players.LocalPlayer

-- 交易系统配置
local TradeConfig = {
    -- 自动接受交易
    autoAccept = false,
    -- 自动发送交易请求
    autoSend = false,
    -- 目标玩家列表
    targetPlayers = {},
    -- 交易物品列表
    tradeItems = {},
    -- 交易间隔时间（秒）
    tradeInterval = 5,
    -- 最大交易次数
    maxTrades = 10
}

-- 交易历史记录
local TradeHistory = {
    sent = {},
    received = {},
    failed = {}
}

-- 日志函数
local function log(s)
    local success, err = pcall(function()
        appendfile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end)
    if not success then
        writefile("log.txt", string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), tostring(s)))
    end
    print("[自动交易] " .. tostring(s))
end

-- 获取游戏服务
local function getGameServices()
    local success, gameEvents = pcall(function()
        return ReplicatedStorage:WaitForChild("GameEvents")
    end)
    
    if not success then
        log("❌ 无法获取GameEvents服务")
        return nil
    end
    
    local tradeEvents = gameEvents:FindFirstChild("TradeEvents")
    if not tradeEvents then
        log("❌ 无法获取TradeEvents服务")
        return nil
    end
    
    return {
        gameEvents = gameEvents,
        tradeEvents = tradeEvents
    }
end

-- 获取玩家背包中的物品
local function getPlayerItems()
    local items = {}
    local backpack = LocalPlayer:FindFirstChild("Backpack")
    
    if backpack then
        for _, item in ipairs(backpack:GetChildren()) do
            if item:IsA("Tool") or item:IsA("StringValue") then
                table.insert(items, {
                    name = item.Name,
                    object = item,
                    type = item.ClassName
                })
        end
    end
end

    -- 获取宠物
    local petsFolder = LocalPlayer:FindFirstChild("Pets")
    if petsFolder then
        for _, pet in ipairs(petsFolder:GetChildren()) do
            if pet:IsA("Model") or pet:IsA("StringValue") then
                table.insert(items, {
                    name = "宠物: " .. pet.Name,
                    object = pet,
                    type = "Pet"
                })
            end
        end
    end
    
    return items
end

-- 获取在线玩家列表
local function getOnlinePlayers()
    local players = {}
    for _, player in ipairs(Players:GetPlayers()) do
        if player ~= LocalPlayer then
            table.insert(players, player)
        end
    end
    return players
end

-- 发送交易请求
local function sendTradeRequest(targetPlayer, items)
    local services = getGameServices()
    if not services then return false end
    
    local success, err = pcall(function()
        -- 发送交易请求
        services.tradeEvents.SendRequest:FireServer(targetPlayer)
        log("📤 向 " .. targetPlayer.Name .. " 发送交易请求")
        
        -- 等待一下再添加物品
        wait(1)
        
        -- 添加物品到交易
        for _, item in ipairs(items) do
            if item.type == "Tool" then
                services.tradeEvents.AddItem:FireServer(item.object)
                log("📦 添加物品: " .. item.name)
            elseif item.type == "StringValue" then
                services.tradeEvents.AddItem:FireServer(item.object.Value)
                log("📦 添加物品: " .. item.name)
        end
    end
    
        -- 确认交易
        services.tradeEvents.Confirm:FireServer()
        log("✅ 确认交易")
    end)
    
    if success then
        table.insert(TradeHistory.sent, {
            time = os.date("%H:%M:%S"),
            target = targetPlayer.Name,
            items = items,
            status = "sent"
        })
        return true
    else
        log("❌ 发送交易请求失败: " .. tostring(err))
        table.insert(TradeHistory.failed, {
            time = os.date("%H:%M:%S"),
            target = targetPlayer.Name,
            error = tostring(err)
        })
    return false
end
end

-- 接受交易请求
local function acceptTradeRequest()
    local services = getGameServices()
    if not services then return false end
    
    local success, err = pcall(function()
        services.tradeEvents.Accept:FireServer()
        log("✅ 接受交易请求")
    end)
    
    if success then
        table.insert(TradeHistory.received, {
            time = os.date("%H:%M:%S"),
            status = "accepted"
        })
        return true
    else
        log("❌ 接受交易失败: " .. tostring(err))
        return false
    end
end

-- 自动交易主循环
local function autoTradeLoop()
    if not TradeConfig.autoSend then return end
    
    local players = getOnlinePlayers()
    local items = getPlayerItems()
    
    if #players == 0 then
        log("⚠️ 没有在线玩家")
        return
    end
    
    if #items == 0 then
        log("⚠️ 背包中没有物品")
        return
    end
    
    -- 选择随机玩家
    local targetPlayer = players[math.random(1, #players)]
    
    -- 选择要交易的物品（最多3个）
    local tradeItems = {}
    local maxItems = math.min(3, #items)
    for i = 1, maxItems do
        table.insert(tradeItems, items[math.random(1, #items)])
    end
    
    log("🎯 开始自动交易: " .. targetPlayer.Name)
    sendTradeRequest(targetPlayer, tradeItems)
end

-- 创建自动交易UI
local function createAutoTradeUI()
    local screenGui = Instance.new("ScreenGui")
    screenGui.Name = "AutoTradeUI"
    screenGui.ResetOnSpawn = false
    screenGui.Parent = LocalPlayer:WaitForChild("PlayerGui")
    
    local mainFrame = Instance.new("Frame")
    mainFrame.Name = "MainFrame"
    mainFrame.Size = UDim2.new(0, 400, 0, 300)
    mainFrame.Position = UDim2.new(0.5, -200, 0.5, -150)
    mainFrame.BackgroundColor3 = Color3.fromRGB(40, 40, 40)
    mainFrame.BorderSizePixel = 0
    mainFrame.Parent = screenGui
    
    -- 边框
    local border = Instance.new("Frame")
    border.Name = "Border"
    border.Size = UDim2.new(1, 4, 1, 4)
    border.Position = UDim2.new(0, -2, 0, -2)
    border.BackgroundColor3 = Color3.fromRGB(100, 100, 100)
    border.BorderSizePixel = 0
    border.Parent = mainFrame
    
    -- 标题
    local titleLabel = Instance.new("TextLabel")
    titleLabel.Name = "Title"
    titleLabel.Size = UDim2.new(1, 0, 0, 30)
    titleLabel.Text = "Grow-a-Garden 自动交易系统"
    titleLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    titleLabel.TextScaled = true
    titleLabel.Font = Enum.Font.SourceSansBold
    titleLabel.BackgroundTransparency = 1
    titleLabel.Parent = mainFrame
    
    -- 关闭按钮
    local closeButton = Instance.new("TextButton")
    closeButton.Name = "CloseButton"
    closeButton.Size = UDim2.new(0, 30, 0, 30)
    closeButton.Position = UDim2.new(1, -35, 0, 5)
    closeButton.Text = "X"
    closeButton.TextColor3 = Color3.fromRGB(255, 255, 255)
    closeButton.BackgroundColor3 = Color3.fromRGB(80, 80, 80)
    closeButton.Parent = mainFrame
    
    -- 自动发送交易开关
    local autoSendFrame = Instance.new("Frame")
    autoSendFrame.Name = "AutoSendFrame"
    autoSendFrame.Size = UDim2.new(1, -20, 0, 40)
    autoSendFrame.Position = UDim2.new(0, 10, 0, 40)
    autoSendFrame.BackgroundColor3 = Color3.fromRGB(50, 50, 50)
    autoSendFrame.BorderSizePixel = 0
    autoSendFrame.Parent = mainFrame
    
    local autoSendLabel = Instance.new("TextLabel")
    autoSendLabel.Name = "Label"
    autoSendLabel.Size = UDim2.new(0.7, 0, 1, 0)
    autoSendLabel.Text = "自动发送交易请求"
    autoSendLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    autoSendLabel.TextScaled = true
    autoSendLabel.Font = Enum.Font.SourceSans
    autoSendLabel.BackgroundTransparency = 1
    autoSendLabel.Parent = autoSendFrame
    
    local autoSendToggle = Instance.new("TextButton")
    autoSendToggle.Name = "Toggle"
    autoSendToggle.Size = UDim2.new(0, 60, 0, 30)
    autoSendToggle.Position = UDim2.new(1, -70, 0.5, -15)
    autoSendToggle.Text = "关闭"
    autoSendToggle.TextColor3 = Color3.fromRGB(255, 255, 255)
    autoSendToggle.BackgroundColor3 = Color3.fromRGB(150, 50, 50)
    autoSendToggle.Parent = autoSendFrame
    
    -- 自动接受交易开关
    local autoAcceptFrame = Instance.new("Frame")
    autoAcceptFrame.Name = "AutoAcceptFrame"
    autoAcceptFrame.Size = UDim2.new(1, -20, 0, 40)
    autoAcceptFrame.Position = UDim2.new(0, 10, 0, 90)
    autoAcceptFrame.BackgroundColor3 = Color3.fromRGB(50, 50, 50)
    autoAcceptFrame.BorderSizePixel = 0
    autoAcceptFrame.Parent = mainFrame
    
    local autoAcceptLabel = Instance.new("TextLabel")
    autoAcceptLabel.Name = "Label"
    autoAcceptLabel.Size = UDim2.new(0.7, 0, 1, 0)
    autoAcceptLabel.Text = "自动接受交易请求"
    autoAcceptLabel.TextColor3 = Color3.fromRGB(255, 255, 255)
    autoAcceptLabel.TextScaled = true
    autoAcceptLabel.Font = Enum.Font.SourceSans
    autoAcceptLabel.BackgroundTransparency = 1
    autoAcceptLabel.Parent = autoAcceptFrame
    
    local autoAcceptToggle = Instance.new("TextButton")
    autoAcceptToggle.Name = "Toggle"
    autoAcceptToggle.Size = UDim2.new(0, 60, 0, 30)
    autoAcceptToggle.Position = UDim2.new(1, -70, 0.5, -15)
    autoAcceptToggle.Text = "关闭"
    autoAcceptToggle.TextColor3 = Color3.fromRGB(255, 255, 255)
    autoAcceptToggle.BackgroundColor3 = Color3.fromRGB(150, 50, 50)
    autoAcceptToggle.Parent = autoAcceptFrame
    
    -- 状态显示
    local statusLabel = Instance.new("TextLabel")
    statusLabel.Name = "Status"
    statusLabel.Size = UDim2.new(1, -20, 0, 100)
    statusLabel.Position = UDim2.new(0, 10, 0, 140)
    statusLabel.Text = "状态: 待机中...\n按 T 键开始/停止自动交易\n按 A 键手动发送交易\n按 R 键查看交易历史"
    statusLabel.TextColor3 = Color3.fromRGB(200, 200, 200)
    statusLabel.TextScaled = true
    statusLabel.Font = Enum.Font.SourceSans
    statusLabel.BackgroundTransparency = 1
    statusLabel.Parent = mainFrame
    
    -- 手动发送交易按钮
    local sendButton = Instance.new("TextButton")
    sendButton.Name = "SendButton"
    sendButton.Size = UDim2.new(0, 100, 0, 30)
    sendButton.Position = UDim2.new(0, 10, 1, -40)
    sendButton.Text = "手动发送"
    sendButton.TextColor3 = Color3.fromRGB(255, 255, 255)
    sendButton.BackgroundColor3 = Color3.fromRGB(70, 130, 70)
    sendButton.Parent = mainFrame
    
    -- 查看历史按钮
    local historyButton = Instance.new("TextButton")
    historyButton.Name = "HistoryButton"
    historyButton.Size = UDim2.new(0, 100, 0, 30)
    historyButton.Position = UDim2.new(0, 120, 1, -40)
    historyButton.Text = "交易历史"
    historyButton.TextColor3 = Color3.fromRGB(255, 255, 255)
    historyButton.BackgroundColor3 = Color3.fromRGB(70, 70, 130)
    historyButton.Parent = mainFrame
    
    -- 事件处理
    closeButton.MouseButton1Click:Connect(function()
        screenGui:Destroy()
    end)
    
    autoSendToggle.MouseButton1Click:Connect(function()
        TradeConfig.autoSend = not TradeConfig.autoSend
        if TradeConfig.autoSend then
            autoSendToggle.Text = "开启"
            autoSendToggle.BackgroundColor3 = Color3.fromRGB(50, 150, 50)
            log("✅ 自动发送交易已开启")
        else
            autoSendToggle.Text = "关闭"
            autoSendToggle.BackgroundColor3 = Color3.fromRGB(150, 50, 50)
            log("❌ 自动发送交易已关闭")
        end
    end)
    
    autoAcceptToggle.MouseButton1Click:Connect(function()
        TradeConfig.autoAccept = not TradeConfig.autoAccept
        if TradeConfig.autoAccept then
            autoAcceptToggle.Text = "开启"
            autoAcceptToggle.BackgroundColor3 = Color3.fromRGB(50, 150, 50)
            log("✅ 自动接受交易已开启")
        else
            autoAcceptToggle.Text = "关闭"
            autoAcceptToggle.BackgroundColor3 = Color3.fromRGB(150, 50, 50)
            log("❌ 自动接受交易已关闭")
        end
    end)
    
    sendButton.MouseButton1Click:Connect(function()
        autoTradeLoop()
    end)
    
    historyButton.MouseButton1Click:Connect(function()
        showTradeHistory()
    end)
    
    return screenGui
end

-- 显示交易历史
local function showTradeHistory()
    log("📊 交易历史统计:")
    log("已发送: " .. #TradeHistory.sent .. " 次")
    log("已接收: " .. #TradeHistory.received .. " 次")
    log("失败: " .. #TradeHistory.failed .. " 次")
    
    if #TradeHistory.sent > 0 then
        log("📤 最近发送的交易:")
        for i = math.max(1, #TradeHistory.sent - 2), #TradeHistory.sent do
            local record = TradeHistory.sent[i]
            log("  " .. record.time .. " - " .. record.target)
        end
    end
end

-- 设置键盘快捷键
local function setupHotkeys()
    UserInputService.InputBegan:Connect(function(input, gameProcessed)
        if gameProcessed then return end
        
        if input.KeyCode == Enum.KeyCode.T then
            TradeConfig.autoSend = not TradeConfig.autoSend
            if TradeConfig.autoSend then
                log("✅ 自动交易已开启")
            else
                log("❌ 自动交易已关闭")
            end
        elseif input.KeyCode == Enum.KeyCode.A then
            autoTradeLoop()
        elseif input.KeyCode == Enum.KeyCode.R then
            showTradeHistory()
        end
    end)
end

-- 自动交易循环
local autoTradeCoroutine = nil

local function startAutoTrade()
    if autoTradeCoroutine then
        task.cancel(autoTradeCoroutine)
    end
    
    autoTradeCoroutine = task.spawn(function()
        while TradeConfig.autoSend do
            autoTradeLoop()
            wait(TradeConfig.tradeInterval)
        end
    end)
end

-- 监听交易状态变化
local function monitorTradeStatus()
    local services = getGameServices()
    if not services then return end
    
    -- 监听交易事件
    for _, event in ipairs(services.tradeEvents:GetChildren()) do
        if event:IsA("RemoteEvent") then
            event.OnClientEvent:Connect(function(...)
                local args = {...}
                log("🟡 收到交易事件: " .. event.Name)
                
                -- 如果是交易请求且开启了自动接受
                if event.Name == "SendRequest" and TradeConfig.autoAccept then
                    wait(1) -- 等待一下
                    acceptTradeRequest()
                end
            end)
        end
    end
end

-- 初始化自动交易系统
local function initializeAutoTrade()
    log("🚀 初始化Grow-a-Garden自动交易系统...")
    
    -- 创建UI
    createAutoTradeUI()
    
    -- 设置快捷键
    setupHotkeys()
    
    -- 监听交易状态
    monitorTradeStatus()
    
    -- 启动自动交易循环
    task.spawn(function()
        while true do
            if TradeConfig.autoSend then
                startAutoTrade()
            end
            wait(1)
        end
    end)
    
    log("✅ 自动交易系统初始化完成")
    log("🎮 快捷键:")
    log("  T - 开启/关闭自动交易")
    log("  A - 手动发送交易")
    log("  R - 查看交易历史")
end

-- 启动系统
initializeAutoTrade()

return {
    config = TradeConfig,
    history = TradeHistory,
    sendTrade = sendTradeRequest,
    acceptTrade = acceptTradeRequest,
    getItems = getPlayerItems,
    getPlayers = getOnlinePlayers
}